import {
  putLocale
} from '../locale.js'

import { RightMenu } from './rightmenu.js'
import LeftPanel from "./LeftPanel.js"
import {docshow} from './docshow.js'
import {ykverify} from './ykverify.js'
import {ytverify} from './ytverify.js'
import {yczs} from './yczs.js'
import {loadingpage} from './loading.js'
import {msginfo} from './msgalert.js'
import $ from "jquery";
import createSvgOpts, { DD, DLQ, DZ, gzpai, BYQ, DKQ, DRQ, FDJ, BLQ, QT, GK, link, LJB, SJB, datatext, barry ,KG,echart,barechart,piechart,gaugechart} from './svgelem_opt.js'
import _ from 'lodash'

const ns = {
  svg: 'http://www.w3.org/2000/svg',
  xlink: 'http://www.w3.org/1999/xlink'
}
/**
 * svg展示
 */
class SvgShow {
  constructor(div = null, url, showLeftPanel,isDebugger) {
    //当前右键菜单
    this.contentMenu = null

    this.isDebugger = isDebugger

    this.showLeftPanel = showLeftPanel

    this.yaokongyuzhiBol = false;

    window.SvgShow = this;

    this.lang = "zh-CN"

    this.goodLangs = ['ar', 'cs', 'de', 'en', 'es', 'fa', 'fr', 'fy', 'hi', 'it', 'ja', 'nl', 'pl', 'pt-BR', 'ro', 'ru', 'sk', 'sl', 'zh-CN', 'zh-TW']
    //当前鼠标聚焦对象
    this.currtSvgObj = null
    //当前展示文档
    this.currentSvgId = "XTT/main"

    this.roleUrl = "/user/profile"

    this.firstLoaded = true

    this.allSvgObjs = {}

    this.lockMap = new Map()

    this.allSvgDefs = {}

    this.allShapes = []

    this.menuBindingElem = null

    this.allSvgElemOpts = new Map()

    this.work = null

    this.rightMenus = {
      "normal": [{ id: "svg-last" }, { id: "svg-next" }, { id: "svg-bigger", class: "separator" }, { id: "svg-litter" },
      { id: "svg-soga" }, { id: "svg-fit" }, { id: "svg-allyx", class: "separator" }, { id: "svg-closeyk" }, { id: "svg-openyk" }, { id: "svg-todaySOE" },{id:"svg-openar"},{id:'svg-openPDR'}],
      "LJB_SJB": [{ id: "svg-byqdoc",opType:"HTTP" }, { id: "svg-biaozpset", class: "separator", children: [{ id: "svg-repair" }, { id: "svg-floor" }, { id: "svg-dangerous" }, { id: "svg-breakedown" },] },
      { id: "svg-ytup",opType:"YT" }, { id: "svg-ytdown",opType:"YT" }, { id: "svg-shutdown" },],
      "datatext": [{ id: "svg-byqdoc",opType:"HTTP" }, { id: "svg-closeyc", class: "separator" }, { id: "svg-openyc" }, { id: "svg-ycset" },
      { id: "svg-yclimit" }, { id: "svg-ycyt", class: "separator",opType:"YT" }, { id: "svg-todayqx", class: "separator" }, { id: "svg-qxmerge" }, { id: "svg-todayOOB" }],
      "gzpai": [{ id: "svg-clearAll",opType:"HTTP" }],
      "KG_DZ_DD": [{ id: "svg-byqdoc",opType:"HTTP" }, { id: "svg-biaozpset", class: "separator", children: [{ id: "svg-repair" }, { id: "svg-floor" }, { id: "svg-dangerous" }, { id: "svg-breakedown" },] },
      { id: "svg-closeyxH" }, { id: "svg-closeyxF" }, { id: "svg-openyx" }, { id: "svg-reveseset" }, { id: "svg-yxpos", class: "separator" }, {
        id: "svg-yk", class: "separator",
        children: [{ id: "svg-H", class: "separator",opType:"YK" }, { id: "svg-F", class: "separator",opType:"YK" }]
      }, { id: "svg-closeyk", class: "separator" ,opType:"YK"},
      { id: "svg-openyk",opType:"YK" },
      // { id: "svg-openjk" }, { id: "svg-closejk" },
      // { id: "svg-todaybw" },
      ],
    }

    this.events =
    {
      "#svg-last": this.bindlastpic,
      "#svg-next": this.bindnextpic,
      "#svg-bigger": this.bindzoombigger,
      "#svg-litter": this.bindzoomlitter,
      "#svg-soga": this.bindzoomsoga,
      "#svg-fit": this.bindzoomfit,
      "#svg-allyx": this.bindallyx,
      "#svg-closeyk": this.bindcloseyk,
      "#svg-openyk": this.bindopenyk,
      "#svg-todaySOE": this.bindopenSoe,
      '#svg-openar':this.bindopenar,
      "#svg-openPDR":this.bindopenPDR,
    }

    this.moveflag = false

    this.zoom = 1

    this.zoommax = 4

    this.zoommin = 0.3

    this.websocketUrl = ""

    this.url = url

    this.$svgShow = div ?? document.getElementById("svgShow")

    this.$svg = document.getElementById("svg")

    this.currentRightMenu = null

    this.svgSource = {}

    this.viewBox = {}

    this.sogaViewBox = {}

    this.svgString = ""

    this.homeButtoId = "svg_56"

    window.svGShow = this

    window.$ = $

    this.history = []

    this.historyIndex = -1

    this.dd = { DD, DLQ, DZ, gzpai, BYQ, DKQ, DRQ, FDJ, BLQ, QT, GK, link, LJB, SJB, datatext, barry ,KG,echart,barechart,piechart,gaugechart}

    this.alarmMusic1 = null

    this.alarmMusic2 = null

    this.alarmMusic3 = null
  }
  setViewBox() {
    if (this.viewBox.x1 < 0 || this.viewBox.y1 < 0) {
      return
    }
    this.svgSource.setAttribute("viewBox", this.viewBox.x + " " + this.viewBox.y + " "
      + this.viewBox.width * this.zoom + " " + this.viewBox.height * this.zoom);

  }

  bindMove() {
    var grabPoint = {};
    var curPoint = {};
    var pos = {
      x: 0,
      y: 0
    };

    this.$svg.addEventListener("dblclick", function (evt) {
      svGShow.moveflag = true;
      grabPoint.x = evt.clientX;
      grabPoint.y = evt.clientY;
      $("#svg").css("cursor", "move");
    });
    this.$svg.addEventListener("mousemove", function (evt) {
      if (!svGShow.moveflag)
        return;
      curPoint.x = evt.clientX;
      curPoint.y = evt.clientY;
      pos.x = (grabPoint.x - curPoint.x) * svGShow.zoom;
      pos.y = (grabPoint.y - curPoint.y) * svGShow.zoom;
      svGShow.svgSource.setAttribute("viewBox", (pos.x + svGShow.viewBox.x) + " "
        + (pos.y + svGShow.viewBox.y) + " " + svGShow.viewBox.width * svGShow.zoom + " "
        + svGShow.viewBox.height * svGShow.zoom);
    });
    this.$svg.addEventListener("mouseup", function (evt) {
      svGShow.viewBox.x = pos.x + svGShow.viewBox.x,
        svGShow.viewBox.y = pos.y + svGShow.viewBox.y,
        pos = {
          x: 0,
          y: 0
        };
      grabPoint = {};
      curPoint = {};
      svGShow.moveflag = false;
      $("#svg").css("cursor", "default");
    });
  }

  bindMouseWheel() {
    var svGShow = this
    this.$svg.addEventListener("mousewheel", function (evt) {
      if (svGShow.moveflag)
        return;
      var delta = evt.wheelDelta;
      if (delta > 0) {
        svGShow.bindzoombigger(svGShow)
      } else {
        svGShow.bindzoomlitter(svGShow)
      }
    })
  }
  bindlastpic(svgShow) {
    if (svgShow.historyIndex > 0) {
      svgShow.historyIndex--
      svgShow.currentSvgId = svgShow.history[svgShow.historyIndex]
      svgShow.loadSvgChart(svgShow.history[svgShow.historyIndex], false)
    }
  }

  bindnextpic(svgShow) {
    if (svgShow.historyIndex < svgShow.history.length - 1) {
      svgShow.historyIndex++
      svgShow.currentSvgId = svgShow.history[svgShow.historyIndex]
      svgShow.loadSvgChart(svgShow.history[svgShow.historyIndex], false)
    }
  }

  bindzoombigger(svgShow) {
    if (svgShow.zoom < svgShow.zoommin) {
      return
    }
    svgShow.zoom -= 0.1
    svgShow.setViewBox()
  }

  bindzoomlitter(svgShow) {
    if (svgShow.zoom > svgShow.zoommax) {
      return
    }
    svgShow.zoom += 0.1
    svgShow.setViewBox()
  }


  bindzoomsoga(svgShow) {
    svgShow.zoom = 1
    svgShow.viewBox = { ...svgShow.sogaViewBox }
    svgShow.setViewBox()
  }

  bindzoomfit(svgShow) {
    svgShow.zoom = 1
    svgShow.viewBox = { ...svgShow.sogaViewBox }
    svgShow.setViewBox()
  }

  bindallyx(svgShow) {
    svgShow.zoom = 1
    svgShow.setViewBox()
  }

  bindcloseyk(svgShow) {
    for(let [key,value] of svgShow.allSvgElemOpts){
      var d = value.data
      if(d.startsWith("2:")>-1 || d.startsWith("30:")>1){
        value.elem.attr("ykclose","true")
      }
    }
  }
  outputSvgData(){
    const event = new CustomEvent('outputSvgData',{
      detail: this
    })
    window.parent.dispatchEvent(event)
  }
  bindopenyk(svgShow) {
    for(let [key,value] of svgShow.allSvgElemOpts){
      var d = value.data
      if(d.startsWith("2:")>-1 || d.startsWith("30:")>1){
        value.elem.removeAttr("ykclose")
      }
    }
  }


  bindopenSoe(svgShow){
    const event=new CustomEvent('openSoe',{
      detail:svgShow
    });
    window.parent.dispatchEvent(event)
  }
  // 事故追忆
  bindopenar(svgShow){
    const event = new CustomEvent('openAr',{
      detail:svgShow
    })
    window.parent.dispatchEvent(event)
  }
  // 人工启动PDR
  bindopenPDR(svgShow){
    const event = new CustomEvent('openPDR',{
      detail:svgShow,
    })
    window.parent.dispatchEvent(event)
  }

  async initRightMenu() {
    var that = this
    for (var key in this.rightMenus) {
      var dialogBox = new RightMenu(this, this.rightMenus[key], "cmenu_" + key, this.i18next, key)
      this.$svg.append(dialogBox)
      dialogBox.setAttribute("id", "rightmenu_" + key)
      dialogBox.init(this.i18next)


      dialogBox.addEventListener('change'+key, function (e) {
        const action = e?.detail?.trigger
        const opType = e?.detail?.opType
        switch (action) {
          case 'delete':
          case 'cut':
          default: {
            if (that.menuBindingElem) {
              that.call(that.menuBindingElem.id, action, {opType:opType})
            } else {
              that.call("-1", action, {})
            }
          }
        }
      }.bind(this))
    }
  }

  initWork() {
    var svGShow = this
    this.work = new Worker("./svgshow/websocketworker.js")
    this.work.onmessage = function (event) {
      var data = event.data;
      if (!!data.code) {
        switch (data.code) {
          case "close":
            work.terminate();
            break
          case "openConnect":
            svGShow.sendWorkRequest({
              code: "sendmsg", data: svGShow.allSvgObjs
            })
            break
          case "closewsconnect":
            break
          case "YC":
          case "YX":
            svGShow.updateSvgObj(data.data)
            break;
          case "HTTP":
            svGShow.updateHttpObj(data.data)
            break;
          case "YK":
          case "YT":
            svGShow.showYkYTResult(data)
            break;
           case "DEfineSend":
            break;
          default:
        }
      }
    }

  }
  // 关闭 websocket功能
  closeWork(){
    this.work.postMessage({code:"close"})
  }
  // 事故反演播放功能
displayAccident(data){
  this.work.postMessage({code:'displayAccident',data:data})
}
  sendWorkRequest(msg) {
    if(msg.data){
      if($("#freshSec").val()!=""){
        msg.data.freshSec = $("#freshSec").val();
      }
    }

    this.work.postMessage(msg)
  }

  parserXml(xml) {
    if (window.DOMParser) {
      var parser = new DOMParser();
      return parser.parseFromString(xml, 'text/xml');
    } else {
      xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
      var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
      xmlDoc.async = 'false';
      xmlDoc.loadXML(xml);
      return xmlDoc;
    }
  }
  supportsSvg_ = function () {
    return !!document.createElementNS
      && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;
  };

  call(id, action, arg) {
    if (this.allSvgElemOpts.get(id)) {
      this.allSvgElemOpts.get(id).call(action, arg)
    } else {
      this.events[action](this)
    }

    return undefined
  }
  /**
   * 根据参数更新svg图形中的元素属性
   * @param {*} msg
   */
  updateSvgObj(data) {
    for(var i=0;i<data.length;i++){
      if (this.allSvgElemOpts.get(data[i].id)) {
        this.call(data[i].id, "update" + data[i].type, data[i])
      }
    }
  }

  updateHttpObj(data){
    if(data==null || data[0].type == "gzpai" )return
    if(data[0].action=="ycset" || data[0].action=="yxset"){
      return
    }
    if(data[0].action=="showTitle"){
      if(data[0].device){
        this.allSvgElemOpts.get(data[0].id).doc = data[0]
        $(this.svgSource).find("title")[0].innerHTML = data[0].device
      }
    }else{
      if(data[0].device){
        this.allSvgElemOpts.get(data[0].id).doc = data[0]
      }
      this.docshow.open(data)
      this.playMusic(this.alarmMusic1)
      // this.playMusic(this.alarmMusic2)
      // this.playMusic(this.alarmMusic3)
    }
  }

  showYkYTResult(data){
    if(data==null){
      return
    }
    if (this.allSvgElemOpts.get(data[0].id)) {
      this.call(data[0].id, data[0].action, data[0])
    }
  }

  /**
   * 获取当前svg对象
   * @param currentId
   */
  getSvgAllObjs(currentId){

  }
  /**
   * 加载svg图形
   * @param {} chartId
   */
  async loadSvgChart(chartName, pushHistory) {
    if (this.firstLoaded) {
      this.firstLoaded = false
    } else {
      if (pushHistory && this.currentSvgId == chartName) {
        //重复图形不加载，但可刷新界面
        return
      }
    }
    this.sendWorkRequest({
      code: "close"
    })
    this.destroySvgDom()
    const response = await fetch(`${this.url}/svg/graphics/file/${chartName}`)
    const xmltext = await response.json()
    if (pushHistory) {
      this.currentSvgId = chartName
      this.history.push(this.currentSvgId)
      this.historyIndex = this.history.length - 1
    }
    this.svgString = decodeURIComponent(escape(atob(xmltext.data[0].content)))
    var t_d = chartName.split("/")
    window.localStorage.setItem('svg-edit-graphicType-display',t_d[0])
    window.localStorage.setItem('svg-edit-graphicDesc-display', t_d[1])
    window.localStorage.setItem('svgedit-pictool', this.svgString)
    const xmlDoc = this.parserXml(this.svgString)
    this.svgSource = xmlDoc.documentElement
    this.svgSource.setAttribute("id", "svgSource")
    var bgurl = this.svgSource.getAttribute("bgurl")
    this.$svg.append(this.svgSource);
    if(bgurl&&bgurl!=""){
      $(this.$svg).css("background-image",`url(${window.serviceUrl}/svg/graphics/previews/${bgurl})`)
    }else{
      $(this.$svg).css("background-image","")
    }
    this.initSvgShow()
    this.initRightMenu()
  }
  /**
   * 读取svg中的所有自定义图元
   */
  initSvgShow() {
    this.allSvgElemOpts.clear()
    this.allSvgObjs = {}
    this.allSvgDefs = {}
    this.allShapes = []
    this.viewBox = {}
    var x = 1600, y = 1600, x_ = 0, y_ = 20;

    x = window.innerWidth - (this.showLeftPanel ? 80 : 0)
    y = window.innerHeight - 2

    const arra = this.svgSource.getAttribute("viewBox").split(" ")
    this.sogaViewBox = {
      x: parseInt(arra[0]),
      y: parseInt(arra[1]),
      width: parseInt(arra[2]),
      height: parseInt(arra[3]),
    }
    this.viewBox = {
      x: parseInt(arra[0]),
      y: parseInt(arra[1]),
      width: parseInt(arra[2]),
      height: parseInt(arra[3]),
    }
    this.svgSource.setAttribute("width", x);
    this.svgSource.setAttribute("height", y);
    // $(this.$svg).find(".gzpai_g").hide();
    $(this.svgSource).attr("aria-label","[title + description]")
    $(this.$svg).css("display", "");
    let emsObjs = $(this.svgSource).find(".ems")
    var that = this
    for (var i = 0; i < emsObjs.length; i++) {
      let ems = $(emsObjs[i])
      ems.attr("style", "pointer-events:bounding-box")
      if (this.allSvgElemOpts.get(emsObjs[i].id)) {
        console.warn("duplicate emsObj:" + emsObjs[i].id)
      }
      var docType = ems.attr("doc-type")
      var data= ems.attr("data")
      var state = ems.attr("state")
      if(docType == "table"){
        continue
      }
      ems.on("mouseover",function(evt){
        var da = evt.target.parentNode.getAttribute("data")
        if(da){
          var dt = evt.target.parentNode.getAttribute("doc-type")
          if(!dt || dt=="gzpai") return
          var did = evt.target.parentNode.getAttribute("id")
          var obj = svGShow.allSvgElemOpts.get(did)
          if(obj.doc){
            $(that.svgSource).find("title")[0].innerHTML = obj.doc.device
            return
          }
          // svGShow.sendWorkRequest({
          //   code: "sendmsg", data: {"HTTP":[{ id: did, type: dt, data: da, action: "showTitle" }]}
          // })
        }else{
          $(that.svgSource).find("title")[0].innerHTML = null
        }
      })
      ems.on("mouseout",function(evt){
          $(that.svgSource).find("title")[0].innerHTML = null
      })
      if(data || state){
        ems.addClass("ems_y")
        if (!this.allSvgObjs[docType]) {
          this.allSvgObjs[docType] = []
        }
        var obj = createSvgOpts(docType, emsObjs[i].id)
        var svgProps = { id: emsObjs[i].id,type:docType, data: obj.data }
        if(docType == "gzpai"){
          return;
          svgProps.pageSize = obj.pageSize
          svgProps.page = 0
          var st = JSON.parse(decodeURIComponent(escape(atob(state))))
          svgProps.filterText = "BMS01-"//st.fliterString;
        }
        this.allSvgObjs[docType].push(svgProps)
        this.allSvgElemOpts.set(emsObjs[i].id, obj)
      }
      if(docType == "datatext"){
        var txt = ems.find("text").text()
        var text = ems.find("text")
        if(text.length>0){
          var foreignObject = document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')
          foreignObject.setAttribute("font-size", text.attr("font-size"))
          foreignObject.setAttribute("font-family", text.attr("font-family"))
          foreignObject.setAttribute("color", text.attr("fill"))
          foreignObject.setAttribute("x", text[0].getBBox().x)
          foreignObject.setAttribute("y", text[0].getBBox().y)
          foreignObject.setAttribute("width", text[0].getBBox().width)
          foreignObject.setAttribute("height", text[0].getBBox().height)
          foreignObject.setAttribute("style", "text-align:right")
          foreignObject.append(txt)
          if(text.attr("transform")){
            foreignObject.setAttribute("transform", text.attr("transform"))
          }
          // foreignObject.append(Math.floor(Math.random()*10000))
          ems.find("text").before(foreignObject)
          ems.find("text").remove()
        }
      }
      if (docType == "link") {
        ems.css("cursor", "pointer")
        ems.on("click", function (evt) {
          var url = evt.target.getAttribute("clink");
          if(url == null || url==""){
            return;
          }
          svGShow.loadSvgChart(url, true)
        })
      }
    }

    let svgDefs = $(this.svgSource).find("defs>*")
    for(var i = 0; i < svgDefs.length; i++){
      var defid= "#"+ svgDefs[i].getAttribute("del")
      if(defid == "#null"){
        continue
      }
      defid = defid.split("_")[0]
      if(!this.allSvgDefs[defid]){
        this.allSvgDefs[defid]=[]
        this.allShapes.push(defid.substring(1))
      }

      var svgDefsId_lgIds = {}
      svgDefsId_lgIds.id = "#"+svgDefs[i].getAttribute("id")
      var linearGradientIds = []
      for(var j=0;j<svgDefs[i].children.length;j++){
        this.getUrlLink(linearGradientIds,svgDefs[i].children[j])
      }
      if(linearGradientIds.length>0){
        svgDefsId_lgIds.lgIds = linearGradientIds
      }
      this.allSvgDefs[defid].push(svgDefsId_lgIds)
    }

    this.sendWorkRequest({
      code: "init", url: this.websocketUrl != "" ?this.websocketUrl:window.wsUrl
    })
  }

  createLg = () => {
    if($("#gzpai_0")[0]==null){
      return
    }
    var tmp = `<svg><defs>
      <symbol del="gzpai_3" id="gzpai_0" viewBox="0 0 150 50" preserveAspectRatio="none">
        <rect fill="#ffffff" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
      </symbol>
      <symbol del="gzpai_3" id="gzpai_1" viewBox="0 0 150 50" preserveAspectRatio="none">
          <rect fill="#ff0000" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
      </symbol>
      <symbol del="gzpai_3" id="gzpai_2" viewBox="0 0 150 50" preserveAspectRatio="none">
          <rect fill="#8f8f8f" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
      </symbol>
      <symbol del="gzpai_3" id="gzpai_3" viewBox="0 0 150 50" preserveAspectRatio="none">
          <rect fill="#0000ff" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
      </symbol>
      <linearGradient id="lgbut" x1="0" x2="0" y1="0" y2="1">
        <stop offset="0" stop-color="#7f7f7f"/>
        <stop offset="0.4" stop-color="#fff"/>
        <stop offset="0.6" stop-color="#fff"/>
        <stop offset="1" stop-color="#7f7f7f"/>
      </linearGradient>
      </svg></defs>`
    var lgs = $(tmp).find("defs>*")
    var defs = $(this.$svg).find("defs")[0]
     $("#gzpai_0").remove()
     $("#gzpai_1").remove()
     $("#gzpai_2").remove()
     $("#gzpai_3").remove()
    defs.append(lgs[0]);
    defs.append(lgs[1]);
    defs.append(lgs[2]);
    defs.append(lgs[3]);
  }

  async reloadSymbol(){
    this.removeDefs()
    const response = await fetch(`${this.url}/svg/primitive/list`)
    const data = (await response.json()).data;
    for (var key in data) {
      if (data[key].length > 0) {
        for (var i = 0; i < data[key].length; i++) {
          if(this.allShapes.indexOf(data[key][i].title)==-1){
            continue
          }
          var reallyimgSrc = decodeURIComponent(escape(atob(data[key][i].content)))
          this.generateDefs(data[key][i].title, reallyimgSrc)
        }
      }
    }
    this.createLg()
    this.initSvgShow()
  }

  generateDefs(shapTitle, dom) {
    var viewBox = $(dom).attr("viewBox")
    var arra = viewBox.split(" ")
    viewBox = `${parseInt(arra[0]) - 5} ${parseInt(arra[1]) - 5}  1400 1100`
    var symbols = new Map()
    var firstSymbolId = {}
    var defs = $(dom).find("defs>*")
    const defsIdMap = new Map()
    if (defs.length > 0) {
      Array.from(defs).forEach((elem, i) => {
        const oldId = elem.id
        const newId = oldId + "_" + shapTitle
        defsIdMap.set(oldId, newId)
        elem.setAttribute('id', newId)
        this.addDefs(elem)
      })
    }
    this.addElement(defsIdMap,firstSymbolId, shapTitle, symbols,null, dom,viewBox)

    symbols.forEach((val,key)=>{
      this.addDefs(val)
    })
  }

  addElement = (defsIdMap,firstSymbolId, shapTitle, defsSymbolMap,curShape, element,viewBox) => {
    let children = $(element).children()
    Array.from(children).forEach((elem, i) => {
      let tagName = elem.tagName;
      if (tagName == 'g') {
        if (elem.classList.contains("layer")) {
          let title = $(elem).find("title")[0]
          var symbolId = shapTitle + "_" + title.textContent.trim().replace(" ", "")
          if (firstSymbolId.id == null) {
            firstSymbolId.id = symbolId
          }
          if (defsSymbolMap.get(symbolId) == null) {
            let childShape = document.createElementNS(ns.svg, 'symbol')
            defsSymbolMap.set(symbolId, childShape)
            childShape.setAttribute("id", symbolId)
            childShape.setAttribute("del", firstSymbolId.id)
            childShape.setAttribute("viewBox", viewBox)
            childShape.setAttribute("preserveAspectRatio", "xMidYMid meet")
            this.addElement(defsIdMap,firstSymbolId, shapTitle, defsSymbolMap,childShape, elem,viewBox);
          }
        }
        else {
          this.addElement(defsIdMap,firstSymbolId, shapTitle, defsSymbolMap,curShape, elem,viewBox);
        }
      } else {
        if (tagName == 'title' || tagName == 'defs') {
          return
        }
        let newElement = $(elem).clone()
        newElement.removeAttr("id")
        let fillAttr = $(elem).attr('fill')
        let strokeAttr = $(elem).attr('stroke')

        const fillAttrId = _.trimEnd(_.trimStart(fillAttr, 'url(#'), ')')
        const strokeAttrId = _.trimEnd(_.trimStart(strokeAttr, 'url(#'), ')')
        if (defsIdMap.has(fillAttrId)) {
          $(newElement).attr('fill', `url(#${defsIdMap.get(fillAttrId)})`)
        }

        if (defsIdMap.has(strokeAttrId)) {
          $(newElement).attr('stroke', `url(#${defsIdMap.get(strokeAttrId)})`)
        }

        $(curShape).append(newElement);
      }
    });
  };

  removeDefs(){
    this.sendWorkRequest({
      code: "close"
    })
    for(var key in this.allSvgDefs){
      var defs = this.allSvgDefs[key]
      defs.forEach(obj => {
        if(obj.id.indexOf("gzpai")>-1){
          return
        }
        $(obj.id).remove()
        if(obj.lgIds){
          obj.lgIds.forEach(id => {
            $(id).remove()
          })
        }
      });
    }
  }

  addDefs(defs){
    $(this.svgSource).find("defs")[0].appendChild(defs)
  }

  getUrlLink(links,elem){
    var fill_attrVal = elem.getAttribute("fill")
    var fill_link = this.getUrlFromAttr(fill_attrVal);
    if(fill_link){
      links.push(fill_link);
    }

    var stroke_attrVal = elem.getAttribute("stroke")
    var stroke_link = this.getUrlFromAttr(stroke_attrVal);
    if(stroke_link){
      links.push(stroke_link);
    }
  }

  getUrlFromAttr(attrVal) {
    if (attrVal) {
      // url('#somegrad')
      if (attrVal.startsWith('url("')) {
        return attrVal.substring(5, attrVal.indexOf('"', 6))
      }
      // url('#somegrad')
      if (attrVal.startsWith("url('")) {
        return attrVal.substring(5, attrVal.indexOf("'", 6))
      }
      if (attrVal.startsWith('url(')) {
        return attrVal.substring(4, attrVal.indexOf(')'))
      }
    }
    return null
  }

  sendHttpRequest() {

  }

  destroySvgDom() {
    $(this.$svg).empty()
  }

  initMusic(){
    this.alarmMusic1 = new Audio("./svgshow/music/aaa.wav");
    this.alarmMusic2 = new Audio("./svgshow/music/bibibi.wav");
    this.alarmMusic3 = new Audio("./svgshow/music/dadada.wav");
  }

  playMusic(music){
    music.play()
    music.currentTime = 0
  }

  initFreshBut(){
    $("#freshSec").on("keyup",function(){
      this.value = this.value.replace(/[^\d]/g, '').replace(/(\d{4})(?=\d)/g, "$1 ");
      if(this.value==0 || this.value== ""){
        this.value = 5
      }
      var data = {
        code: "sendmsg", data: svGShow.allSvgObjs
      }
      // svGShow.sendWorkRequest(data)
      this.select();
    })
  }

  toShow(){
     console.log("我执行show")
  }

  async getRole(){
    const response = await fetch(`${this.url}${this.roleUrl}`)
    const text = await response.json()
  }

  async init() {
    const { i18next } = await putLocale(this.lang, this.goodLangs)
    this.i18next = i18next
    window.i18next = i18next
    await import('./seButton.js')
    await import('./seExpand.js')
    this.initWork()
    // if (window.parent.showLeftPanel) {
    //   this.showLeftPanel = true
    //   window.parent.showLeftPanel = false
    // }
    if (this.showLeftPanel) {
      this.leftPanel = new LeftPanel(this)
      this.leftPanel.init()
      if (window.localStorage) {
        this.currentSvgId = window.localStorage.getItem("svg-edit-graphicType-display") +"/" +window.localStorage.getItem("svg-edit-graphicDesc-display")
        if(this.currentSvgId.indexOf("null")>-1){
          this.currentSvgId = "XTT/main"
        }
      }
    }else{
      var mainLink = window.localStorage.getItem("over-view-display")
      if(mainLink && mainLink == "true"){
        this.currentSvgId = window.localStorage.getItem("svg-edit-graphicType-display") +"/" +window.localStorage.getItem("svg-edit-graphicDesc-display")
        window.localStorage.removeItem("over-view-display")
      }else{
        this.currentSvgId = "XTT/main"
      }
    }
    this.docshow = new docshow(this)
    this.ykverify = new ykverify(this)
    this.ytverify = new ytverify(this)
    this.yczs = new yczs(this)
    this.loadingpage = new loadingpage(this)
    this.msginfo = new msginfo(this)
    await this.loadSvgChart(this.currentSvgId, true)
    // this.bindMouseWheel()
    this.bindMove()
    this.initMusic()
    this.initFreshBut()
    this.outputSvgData()
    // this.getRole()

  }
}

export default SvgShow
